class_name Door
extends Node2D

@warning_ignore("unused_signal")
signal opened


@onready var frontSprite: Sprite2D = $DoorSprite
@onready var enemies: Node2D = $Enemies

## 开门的时长
@export var duration_open: float = 1.0
## 门中敌人的生成频率（秒）
@export var duration_spawn_enemy: float = 6.0


var door_height: float = 0.0
var is_opened: bool = false

# 敌人生成数据
var enemy_datas: Array[EnemyData] = []
# 活动的敌人数量
var active_enemy_counter: int = 0
# 已生成的敌人数量
var created_enemy_counter: int = 0
# 生成敌人的总数量
var created_enemy_total: int

var _tween: Tween
var _spawn_enemy_time: float = 0.0


func _ready():
	door_height = frontSprite.texture.get_height()
	init_enemy_datas()
	created_enemy_total = enemy_datas.size()
	_spawn_enemy_time = duration_spawn_enemy


func _process(delta: float):
	if not is_opened:
		return
	if can_create_enemies():
		create_enemies()
	if is_opened:
		_spawn_enemy_time -= delta


## 是否全部敌人已死
func is_all_enemies_death() -> bool:
	return created_enemy_counter == created_enemy_total and active_enemy_counter == 0


func open():
	if is_opened:
		return
	_tween = get_tree().create_tween()
	_tween.tween_property(frontSprite, "position", Vector2.UP * door_height, duration_open).set_ease(Tween.EASE_OUT)
	_tween.tween_callback(on_tween_opened)



func on_tween_opened():
	call_deferred("create_enemies")
	is_opened = true
	opened.emit()
	_tween.call_deferred("kill")


func init_enemy_datas():
	for placeholder: EnemyPlaceHolder in enemies.get_children():
		var enemy_data = placeholder.enemy_data
		enemy_data.origin_point = placeholder.global_position
		enemy_datas.push_back(enemy_data)
		placeholder.queue_free()


func can_create_enemies() -> bool:
	return _spawn_enemy_time < 0.0 and created_enemy_counter < created_enemy_total



func create_enemies():
	var data: Variant = enemy_datas.pop_front()
	if data == null:
		return
	active_enemy_counter += 1
	created_enemy_counter += 1
	_spawn_enemy_time = duration_spawn_enemy
	StageManager.spawn_enemy_in_door(data, self)


func on_enemy_death(_enemy: Character):
	if not is_opened:
		return
	active_enemy_counter -= 1
